package com.wyix.config;

import com.wyix.interceptor.AuthInterceptor;
import com.wyix.properties.AuthProperties;
import com.wyix.service.AuthService;
import com.wyix.service.impl.AuthServiceImpl;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 权限认证自动配置类，实现Starter的自动配置逻辑
 */
@Configuration
@ConditionalOnClass(AuthService.class)  // 当类路径下存在AuthService时才生效
@EnableConfigurationProperties(AuthProperties.class)  // 启用配置属性
public class AuthAutoConfiguration {
    /**
     * 当容器中没有AuthService实例时，自动创建一个
     */
    @Bean
    @ConditionalOnMissingBean
    public AuthService authService(AuthProperties properties) {
        return new AuthServiceImpl(properties);
    }

    /**
     * 注册权限认证拦截器
     */
    @Bean
    @ConditionalOnMissingBean
    public AuthInterceptor authInterceptor(AuthService authService, AuthProperties properties) {
        return new AuthInterceptor(authService, properties);
    }

    /**
     * 仅在Web应用中才注册拦截器到Spring MVC
     */
    @Configuration
    @ConditionalOnWebApplication
    @ConditionalOnMissingBean(name = "authWebMvcConfigurer")
    public static class AuthWebMvcConfigurer implements WebMvcConfigurer {

        private final AuthInterceptor authInterceptor;
        private final AuthProperties authProperties;

        public AuthWebMvcConfigurer(AuthInterceptor authInterceptor, AuthProperties authProperties) {
            this.authInterceptor = authInterceptor;
            this.authProperties = authProperties;
        }

        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            // 如果权限认证未启用，则不注册拦截器
            if (!authProperties.isEnabled()) {
                return;
            }

            // 注册拦截器，并配置拦截路径和排除路径
            registry.addInterceptor(authInterceptor)
                    .addPathPatterns(authProperties.getIncludePaths())
                    .excludePathPatterns(authProperties.getExcludePaths());
        }
    }
}
